'use strict'

/**
 * 方法类
 */
//------------------------------------------------------------------
import utils from './utils'
import apiCls from './api'
import routerCls from './router'
import storeCls from './store'
import { store as fast_store } from './store'
//------------------------------------------------------------------

/**
 * 全局加载模板
 */
const fast_templates = [
]

/**
 * 全局加载插件
 */
const fast_components = [
]

/**
 * 安装方法类和插件
 *
 * @param app 实例
 * @param options 入参
 */
const install = (app, options) => {
    options.plugins = options.plugins || []
    options.plugins.push(plugin)

    // 注册组件, 加载所有plugin的组件
    let components = []
    let apiPool = {}
    let routers = []
    if (options.plugins) {
        for(let i = 0; i < options.plugins.length; i++) {
            let plugin = options.plugins[i]
            if (plugin.api) {
                for(let key in plugin.api) {
                    apiPool[ plugin.name + "." + key ] = plugin.api[key]
                }
            }
            // 加载全部路由
            if (plugin.router) routers.push(...plugin.router)
            // 加载全部插件
            if (plugin.components) components.push(...plugin.components)
            // 加载全部模板
            if (plugin.templates) components.push(...plugin.templates)
        }
    }

    let api = new apiCls({ pool: apiPool })
    let fastStore = new storeCls(options).instance()
    let fastRouter = new routerCls({
        historyMode: import.meta.env.VITE_APP_ROUTER_MODE, base: import.meta.env.VITE_APP_ROUTER_BASE,
        routers,
        ...route,
        ...options.router }).instance()

    // 全局加载方法类
    app.config.globalProperties.$api = api
    app.config.globalProperties.$utils = utils
    app.config.globalProperties.$routeUrl = utils.routeUrl(fastRouter)

    // 加载路由器
    app.use(fastRouter)
    // 加载store
    app.use(fastStore)

    for(let i = 0; i < components.length; i++) {
        app.component(components[i].name, components[i])
    }
}

// 作为插件导出
export const plugin = {
    name: 'fast',
    components: fast_components,
    templates: fast_templates,
    store: fast_store
}

// 导出fast系统提供基础功能
export const route = {
    $error404: import('./views/error/404.vue'),
    $motherboard: import('./views/motherboard/default.vue')
}

export {
    utils
}

export default {
    install
}
